import 'package:flutter/material.dart';
import '../models/exam_model.dart';
import '../models/question_model.dart';
import '../services/exam_service.dart';
import '../services/file_select_service.dart';
import 'package:permission_handler/permission_handler.dart';
import 'dart:io';

class CreateExamScreen extends StatefulWidget {
  const CreateExamScreen({super.key});

  @override
  State<CreateExamScreen> createState() => _CreateExamScreenState();
}

class _CreateExamScreenState extends State<CreateExamScreen> {
  final _formKey = GlobalKey<FormState>();
  final _titleController = TextEditingController();
  final _descriptionController = TextEditingController();
  final _durationController = TextEditingController(text: '60');
  
  List<Question> _questions = [];
  bool _isCreating = false;

  @override
  void dispose() {
    _titleController.dispose();
    _descriptionController.dispose();
    _durationController.dispose();
    super.dispose();
  }

  void _addSingleChoiceQuestion() {
    setState(() {
      // 添加一个示例单选题
      _questions.add(
        SingleChoiceQuestion(
          id: 'q${_questions.length + 1}',
          text: '新的单选题',
          score: 10,
          choices: [
            Choice(id: 'A', text: '选项A'), 
            Choice(id: 'B', text: '选项B'), 
            Choice(id: 'C', text: '选项C'), 
            Choice(id: 'D', text: '选项D')
          ],
          correctOption: 0, // 默认第一个选项为正确答案
        ),
      );
    });
  }

  void _addMultipleChoiceQuestion() {
    setState(() {
      // 添加一个示例多选题
      _questions.add(
        MultipleChoiceQuestion(
          id: 'q${_questions.length + 1}',
          text: '新的多选题',
          score: 10,
          choices: [
            Choice(id: 'A', text: '选项A'), 
            Choice(id: 'B', text: '选项B'), 
            Choice(id: 'C', text: '选项C'), 
            Choice(id: 'D', text: '选项D')
          ],
          correctOptions: [0, 1], // 默认前两个选项为正确答案
        ),
      );
    });
  }

  void _addFillBlankQuestion() {
    setState(() {
      // 添加一个示例填空题
      _questions.add(
        FillBlankQuestion(
          id: 'q${_questions.length + 1}',
          text: '请填写____',
          score: 10,
          correctAnswer: '正确答案',
        ),
      );
    });
  }

  void _addTrueOrFalseQuestion() {
    setState(() {
      // 添加一个示例判断题
      _questions.add(
        TrueOrFalseQuestion(
          id: 'q${_questions.length + 1}',
          text: '这是一个判断题',
          score: 5,
          correctAnswer: true, // 默认为正确
        ),
      );
    });
  }

  void _addShortAnswerQuestion() {
    setState(() {
      // 添加一个示例简答题
      _questions.add(
        ShortAnswerQuestion(
          id: 'q${_questions.length + 1}',
          text: '请简要回答以下问题',
          score: 20,
          referencedAnswer: '参考答案',
        ),
      );
    });
  }

  void _createExam() {
    if (_formKey.currentState!.validate()) {
      setState(() {
        _isCreating = true;
      });

      // 创建考试
      try {
        String id = 'exam${DateTime.now().millisecondsSinceEpoch}';
        // 计算总分
        int totalScore = _questions.fold(0, (sum, q) => sum + q.score);
        
        Exam exam = Exam(
          id: id,
          title: _titleController.text,
          description: _descriptionController.text,
          duration: int.parse(_durationController.text),
          questions: _questions,
          totalScore: totalScore,
        );

        // 添加到考试列表
        ExamService.addExam(exam);

        setState(() {
          _isCreating = false;
        });

        // 返回上一页
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('考试创建成功')),
        );
        Navigator.pop(context);
      } catch (e) {
        setState(() {
          _isCreating = false;
        });
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('创建失败: $e')),
        );
      }
    }
  }

  // 从Excel文件导入考试
  void _importFromExcelFile() async {
    // 验证基本信息
    if (!_validateBasicInfo()) {
      return;
    }
    
    // 请求存储权限
    final status = await Permission.storage.request();
    if (!status.isGranted) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('需要存储权限来访问Excel文件'))
      );
      return;
    }
    
    // 显示加载对话框
    setState(() {
      _isCreating = true;
    });
    
    try {
      // 使用FileSelectService选择Excel文件
      File? excelFile = await FileSelectService.pickExcelFile();
      
      if (excelFile == null) {
        setState(() {
          _isCreating = false;
        });
        // 用户取消了选择
        return;
      }
      
      // 从Excel文件创建考试
      final exam = await ExamService.createExamFromExcelFile(
        excelFile,
        title: _titleController.text,
        description: _descriptionController.text,
        duration: int.parse(_durationController.text),
      );
      
      setState(() {
        _isCreating = false;
      });
      
      if (exam != null) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('从Excel文件导入试题成功')),
        );
        Navigator.pop(context);
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('导入失败，请检查Excel文件格式')),
        );
      }
    } catch (e) {
      setState(() {
        _isCreating = false;
      });
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('导入错误: $e')),
      );
    }
  }
  
  // 生成Excel模板
  void _generateExcelTemplate() async {
    // 请求存储权限
    final status = await Permission.storage.request();
    if (!status.isGranted) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('需要存储权限来生成Excel模板文件'))
      );
      return;
    }
    
    // 显示加载对话框
    _showLoadingDialog('正在生成Excel模板...');
    
    try {
      // 生成Excel模板
      final templatePath = await ExamService.generateExamExcelTemplate();
      
      // 关闭加载对话框
      Navigator.pop(context);
      
      if (templatePath != null) {
        // 显示成功对话框
        _showTemplateSuccessDialog(templatePath);
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('生成模板失败')),
        );
      }
    } catch (e) {
      // 关闭加载对话框
      Navigator.pop(context);
      
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('生成模板错误: $e')),
      );
    }
  }
  
  // 显示模板生成成功对话框
  void _showTemplateSuccessDialog(String path) {
    final file = File(path);
    final directory = file.parent.path;
    final fileName = file.path.split('/').last;
    
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('模板创建成功'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text('模板文件已保存到:'),
            const SizedBox(height: 8),
            Container(
              padding: const EdgeInsets.all(8),
              decoration: BoxDecoration(
                color: Colors.grey.shade200,
                borderRadius: BorderRadius.circular(4),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '文件夹: $directory',
                    style: const TextStyle(fontFamily: 'monospace', fontSize: 12),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    '文件名: $fileName',
                    style: const TextStyle(fontFamily: 'monospace', fontSize: 12),
                  ),
                ],
              ),
            ),
            const SizedBox(height: 16),
            const Text('请使用电子表格应用打开此文件，填入考试题目后保存。'),
            const SizedBox(height: 12),
            Text(
              '提示：在Android手机上，可以在"文件管理"应用中的"下载"文件夹中找到ExamApp目录。', 
              style: TextStyle(
                color: Colors.blue.shade700,
                fontSize: 13,
                fontStyle: FontStyle.italic,
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }
  
  // 显示加载对话框
  void _showLoadingDialog(String message) {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => AlertDialog(
        content: Row(
          children: [
            const CircularProgressIndicator(),
            const SizedBox(width: 20),
            Text(message),
          ],
        ),
      ),
    );
  }

  // 导入内置Excel题目
  void _importFromBuiltinExcel() async {
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('此功能已移除，请使用"从Excel导入"功能导入试题文件'),
        duration: Duration(seconds: 3),
      ),
    );
  }
  
  // 验证基本信息
  bool _validateBasicInfo() {
    if (!_formKey.currentState!.validate()) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('请填写完整的考试基本信息')),
      );
      return false;
    }
    return true;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('创建新考试'),
        backgroundColor: Colors.blue.shade800,
        foregroundColor: Colors.white,
      ),
      body: _isCreating 
          ? const Center(child: CircularProgressIndicator())
          : SingleChildScrollView(
              padding: const EdgeInsets.all(16.0),
              child: Form(
                key: _formKey,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 基本信息
                    Card(
                      elevation: 2,
                      margin: const EdgeInsets.only(bottom: 24),
                      child: Padding(
                        padding: const EdgeInsets.all(16),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            const Text(
                              '基本信息',
                              style: TextStyle(
                                fontSize: 18,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            const SizedBox(height: 16),
                            TextFormField(
                              controller: _titleController,
                              decoration: const InputDecoration(
                                labelText: '考试标题',
                                border: OutlineInputBorder(),
                              ),
                              validator: (value) {
                                if (value == null || value.isEmpty) {
                                  return '请输入考试标题';
                                }
                                return null;
                              },
                            ),
                            const SizedBox(height: 16),
                            TextFormField(
                              controller: _descriptionController,
                              decoration: const InputDecoration(
                                labelText: '考试描述',
                                border: OutlineInputBorder(),
                              ),
                              maxLines: 3,
                              validator: (value) {
                                if (value == null || value.isEmpty) {
                                  return '请输入考试描述';
                                }
                                return null;
                              },
                            ),
                            const SizedBox(height: 16),
                            TextFormField(
                              controller: _durationController,
                              decoration: const InputDecoration(
                                labelText: '考试时长（分钟）',
                                border: OutlineInputBorder(),
                              ),
                              keyboardType: TextInputType.number,
                              validator: (value) {
                                if (value == null || value.isEmpty) {
                                  return '请输入考试时长';
                                }
                                try {
                                  int duration = int.parse(value);
                                  if (duration <= 0) {
                                    return '考试时长必须大于0';
                                  }
                                } catch (e) {
                                  return '请输入有效的数字';
                                }
                                return null;
                              },
                            ),
                          ],
                        ),
                      ),
                    ),
                    
                    // 题目列表
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        const Text(
                          '考试题目',
                          style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        Wrap(
                          spacing: 8.0,
                          runSpacing: 8.0,
                          children: [
                            ElevatedButton.icon(
                              onPressed: _generateExcelTemplate,
                              icon: const Icon(Icons.download),
                              label: const Text('生成Excel模板'),
                              style: ElevatedButton.styleFrom(
                                backgroundColor: Colors.orange.shade700,
                                foregroundColor: Colors.white,
                              ),
                            ),
                            ElevatedButton.icon(
                              onPressed: _importFromExcelFile,
                              icon: const Icon(Icons.upload_file),
                              label: const Text('从Excel导入'),
                              style: ElevatedButton.styleFrom(
                                backgroundColor: Colors.purple.shade700,
                                foregroundColor: Colors.white,
                              ),
                            ),
                            ElevatedButton.icon(
                              onPressed: _importFromBuiltinExcel,
                              icon: const Icon(Icons.table_chart),
                              label: const Text('从内置Excel导入'),
                              style: ElevatedButton.styleFrom(
                                backgroundColor: Colors.green.shade700,
                                foregroundColor: Colors.white,
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                    const SizedBox(height: 16),
                    
                    // 添加题目按钮部分 - 放到单独的 Card 中
                    Card(
                      margin: const EdgeInsets.only(bottom: 16),
                      child: Padding(
                        padding: const EdgeInsets.all(12.0),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            const Text(
                              '手动添加题目:',
                              style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                            const SizedBox(height: 12),
                            Wrap(
                              spacing: 8.0,
                              runSpacing: 8.0,
                              children: [
                                ElevatedButton.icon(
                                  onPressed: _addSingleChoiceQuestion,
                                  icon: const Icon(Icons.radio_button_checked, size: 18),
                                  label: const Text('单选题'),
                                  style: ElevatedButton.styleFrom(
                                    backgroundColor: Colors.blue,
                                    foregroundColor: Colors.white,
                                  ),
                                ),
                                ElevatedButton.icon(
                                  onPressed: _addMultipleChoiceQuestion,
                                  icon: const Icon(Icons.check_box, size: 18),
                                  label: const Text('多选题'),
                                  style: ElevatedButton.styleFrom(
                                    backgroundColor: Colors.teal,
                                    foregroundColor: Colors.white,
                                  ),
                                ),
                                ElevatedButton.icon(
                                  onPressed: _addFillBlankQuestion,
                                  icon: const Icon(Icons.horizontal_rule, size: 18),
                                  label: const Text('填空题'),
                                  style: ElevatedButton.styleFrom(
                                    backgroundColor: Colors.amber.shade800,
                                    foregroundColor: Colors.white,
                                  ),
                                ),
                                ElevatedButton.icon(
                                  onPressed: _addTrueOrFalseQuestion,
                                  icon: const Icon(Icons.fact_check, size: 18),
                                  label: const Text('判断题'),
                                  style: ElevatedButton.styleFrom(
                                    backgroundColor: Colors.indigo,
                                    foregroundColor: Colors.white,
                                  ),
                                ),
                                ElevatedButton.icon(
                                  onPressed: _addShortAnswerQuestion,
                                  icon: const Icon(Icons.short_text, size: 18),
                                  label: const Text('简答题'),
                                  style: ElevatedButton.styleFrom(
                                    backgroundColor: Colors.deepPurple,
                                    foregroundColor: Colors.white,
                                  ),
                                ),
                              ],
                            ),
                          ],
                        ),
                      ),
                    ),
                    
                    if (_questions.isEmpty)
                      const Center(
                        child: Text(
                          '暂无题目，点击"添加题目"按钮添加',
                          style: TextStyle(color: Colors.grey),
                        ),
                      )
                    else
                      // 题目列表
                      ListView.builder(
                        shrinkWrap: true,
                        physics: const NeverScrollableScrollPhysics(),
                        itemCount: _questions.length,
                        itemBuilder: (context, index) {
                          final question = _questions[index];
                          return Card(
                            margin: const EdgeInsets.only(bottom: 16),
                            child: ListTile(
                              title: Text(question.text),
                              subtitle: Text('分值: ${question.score}分'),
                              trailing: IconButton(
                                icon: const Icon(Icons.delete, color: Colors.red),
                                onPressed: () {
                                  setState(() {
                                    _questions.removeAt(index);
                                  });
                                },
                              ),
                            ),
                          );
                        },
                      ),
                    
                    const SizedBox(height: 24),
                    
                    // 创建按钮
                    SizedBox(
                      width: double.infinity,
                      child: ElevatedButton(
                        onPressed: _questions.isEmpty ? null : _createExam,
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.blue.shade800,
                          foregroundColor: Colors.white,
                          padding: const EdgeInsets.symmetric(vertical: 16),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(8),
                          ),
                        ),
                        child: const Text(
                          '创建考试',
                          style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
    );
  }
} 